package com.nhim.cms.admin.server;

import java.util.ArrayList;
import java.util.List;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.nhim.cms.admin.client.rpc.ContentTypeElementDefinitionRPCService;
import com.nhim.cms.admin.shared.ContentTypeElementDefinitionRPCProxy;
import com.nhim.cms.dao.ContentTypeElementDefinitionDAO;
import com.nhim.cms.domain.ContentTypeElementDefinition;
import com.nhim.cms.util.ContentTypeElementDefinitionManager;

public class ContentTypeElementDefinitionRPCServiceImpl extends
		RemoteServiceServlet implements ContentTypeElementDefinitionRPCService {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public List<ContentTypeElementDefinitionRPCProxy> findByContentTypeId(
			Integer contentTypeId) throws IllegalArgumentException {
		List<ContentTypeElementDefinitionRPCProxy> result = new ArrayList<ContentTypeElementDefinitionRPCProxy>();
		try {
			List<ContentTypeElementDefinition> contentTypeElementDefinitionList = ContentTypeElementDefinitionDAO
					.getInstance().findByContentTypeId(contentTypeId);
			if (contentTypeElementDefinitionList != null
					&& contentTypeElementDefinitionList.size() > 0) {
				for (ContentTypeElementDefinition cTypeEle : contentTypeElementDefinitionList)
					result.add(toProxy(cTypeEle));

			}

		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
		return result;
	}

	private ContentTypeElementDefinitionRPCProxy toProxy(
			ContentTypeElementDefinition cTypeEle) {
		return new ContentTypeElementDefinitionRPCProxy(cTypeEle.getId(),
				cTypeEle.getDescription(), cTypeEle.getPosition(),
				cTypeEle.getIsRequired(), cTypeEle.getElementDefinition()
						.getName(), cTypeEle.getElementDefinition()
						.getIsMetadata(), cTypeEle.getElementDefinition()
						.getId(), cTypeEle.getContentType().getId());

	}

	public Boolean persitContentTypeElementDefinitioinsIdandPositionOnly(
			Integer contentTypeId, List<Integer> elementDefinitionIds)
			throws IllegalArgumentException {
		return ContentTypeElementDefinitionManager.getInstance()
				.persitContentTypeElementDefinitioinsIdandPositionOnly(
						contentTypeId, elementDefinitionIds);

	}

	public Boolean persitContentTypeElementDefinitioinsIsRequiredAndDescriptionOnly(
			List<ContentTypeElementDefinitionRPCProxy> list)
			throws IllegalArgumentException {
		try {
			for (ContentTypeElementDefinitionRPCProxy proxy : list) {
				ContentTypeElementDefinition entity = ContentTypeElementDefinitionDAO
						.getInstance().findById(proxy.getId());
				if (entity != null) {
					entity.setIsRequired(proxy.getIsRequired());
					entity.setDescription(proxy.getDescription());
					ContentTypeElementDefinitionManager.getInstance()
							.saveOrUpdate(entity);
				}
			}
			return true;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return false;

	}

}
